/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.tools.StrUtil;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.OrgManager;
import com.apache.uct.util.UctStringUtil;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * description:  获取用户列表插件
 *
 * @author iussoft 创建时间：2016-3-25
 */
public class UserListPlugin implements PluginConnector {

    private IDao userDao;

    private Logger log = Logger.getLogger(UserListPlugin.class);

    private OrgManager orgManager;

    /**
     * TODO 获取用户列表插件.  <br>
     * 参数说明:<br>
     * roleId: 角色ID 或 roleEname:角色标识;获取用户列表<br>
     * user属性:按用户属性获取用户列表<br>
     * 分页设置:<br>
     * pageSize:每页记录数;<br>
     * pageIndex:当前页码
     */
    public Object execute(ParamsVo vo) throws Exception {
        String orderBy = "create_time";
        ResultEntity result = new ResultEntity();
        try {
            result.setResult("true");
            String roleId = String.valueOf(vo.getParams("roleId"));
            String roleEname = String.valueOf(vo.getParams("roleEname"));
            MethodParam param = null;
            if (Validator.isNotNull(roleId) || Validator.isNotNull(roleEname)) {
                if (Validator.isNotNull(roleId)) {//按角色ID获取用户列表
                    param = new MethodParam("UsersByRoleId", "", "", User.class.getName());
                    param.setParams("roleId", roleId);
                    param.setSqlStr(userDao.getSql(2)
                            + " and userId in(select userId from RoleGive where roleId=:roleId)");
                } else if (Validator.isNotNull(roleEname)) {//按角色标识获取用户列表
                    param = new MethodParam("UsersByRoleId", "", "", User.class.getName());
                    param.setParams("roleEname", roleEname);
                    param.setSqlStr(userDao.getSql(2)
                            + " and userId in(select userId from RoleGive where roleEname=:roleEname)");
                }
            } else {
                param = setMethodParams(vo, 2, orderBy);
            }
            if (Validator.isEmpty(param)) {
                result.setMessage("查询条件为空或不存在相关信息");
                return result;
            }
            String prows = Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")),
                    String.valueOf(vo.getParams("rows")));
            String ppage = Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")),
                    String.valueOf(vo.getParams("page")));
            int pageSize = Integer.valueOf(Validator.getDefaultStr(prows, "0"));
            int pageIndex = Integer.valueOf(Validator.getDefaultStr(ppage, "0"));
            param.setResultCache(false);//关闭查询结果集缓存
            param.setOrderby(orderBy + " desc");
            if (pageSize == 0 && pageIndex == 0) {
                List list = userDao.select(param);
                result.setEntity(list);
            } else {
                param.setPageIndex(pageIndex);
                param.setPageSize(pageSize);
                Page page = userDao.pageSelect(param);
                result.setEntity(page);
            }
        } catch (Exception e) {
            result.setResult("false");
            log.error("执行用户查询失败 ", e);
            result.setMessage("用户查询失败！");
        }
        return result;
    }

    private MethodParam setMethodParams(ParamsVo vo, int type, String orderBy) {
        StringBuffer sb = new StringBuffer(userDao.getSql(type));
        MethodParam param = new MethodParam("ByProperty", "", "", User.class.getName());
        String all = String.valueOf(vo.getParams("userAll"));//获取所有用户列表
        if (Validator.isNull(all)) {
            String str = getUserParams(param, vo);
            if (Validator.isNull(str))
                return null;
            sb.append(str);
        }
        String status = String.valueOf(vo.getParams("userStatus"));
        if (Validator.isNotNull(status)) {
            param.setParams("userStatus", status);
        } else {
            sb.append(" and userStatus>-1");
        }
        //		String userEname = String.valueOf(vo.getParams("userEname"));
        //		if (Validator.isNotNull(userEname)) {
        //			param.setParams("userEname", userEname);
        //		}
        if (Validator.isNotNull(orderBy)) {
            sb.append(" order by " + UctStringUtil.toCamelNamed(orderBy) + " desc");
        }
        param.setSqlStr(sb.toString());
        return param;
    }

    //组织用户信息查询条件
    private String getUserParams(MethodParam param, ParamsVo vo) {
        StringBuffer sb = new StringBuffer();
        if (Validator.isNotNull(String.valueOf(vo.getParams("userIds")))) {
            String ids = getUserIds(String.valueOf(vo.getParams("userIds")));
            sb.append(" and userId in(" + ids + ")");
            param.setParams("userIds", ids);
            return sb.toString();
        }
        /**操作权限条件  权限ID用户,角ID,机构ID    */
        if (Validator.isNotNull(String.valueOf(vo.getParams("actId")))) {
            String actId = String.valueOf(vo.getParams("actId"));
            StringBuffer actStr = new StringBuffer();
            actStr.append(" and (");
            actStr.append(
                    " userId in ( select roleId from ActGive where actId='" + actId + "' )");//
            actStr.append(" or userId in ( ");
            actStr.append(" select userId from RoleGive where roleId in(");
            actStr.append(" select roleId from ActGive where actId ='" + actId + "' )");
            actStr.append(" ) ) ");
            sb.append(actStr.toString());
            param.setParams("actStr", getactStr(actId));
        }

        /**操作权限条件  角色ID */
        if (Validator.isNotNull(String.valueOf(vo.getParams("flowRoleId")))) {
            String roleId = String.valueOf(vo.getParams("flowRoleId"));
            StringBuffer actStr = new StringBuffer();
            actStr.append(" and userId in ( select userId from RoleGive where roleId='" + roleId
                    + "' )");//
            sb.append(actStr.toString());
            param.setParams("roleStr", getRoleIdStr(roleId));
        }

        /**权限标识*/
        if (StrUtil.isNotNull(String.valueOf(vo.getParams("actEname")))) {
            String actEname = String.valueOf(vo.getParams("actEname"));
            StringBuffer str = new StringBuffer();
            str.append(" and (");
            str.append(
                    " userId in (select roleId from ActGive where actId in (select actId from Act where actEname='"
                            + actEname + "') )");
            str.append(
                    " or userId in (select roleId from RoleGive where roleId in(select roleId from ActGive where actId in(select actId from Act where actEname='"
                            + actEname + "')) )");
            str.append(" ) ");
            sb.append(str.toString());
            param.setParams("actEnameStr", actEnameStr(actEname));
        }

        /**部门数据权限条件*/
        if (StrUtil.isNotNull(String.valueOf(vo.getParams("dataDeptId")))) {
            String dataDept = String.valueOf(vo.getParams("dataDeptId"));
            sb.append(
                    " and userId in( select userId from DataRight where dataName='dept' and dataKey='"
                            + dataDept + "' )");
            param.setParams("dataDeptStr",
                    " and user_Id in( select user_Id from uct_data_right where data_Name='dept' and data_Key='"
                            + dataDept + "' )");
        } else {
            String deptIds = String.valueOf(vo.getParams("dataDeptIds"));
            if (Validator.isNotNull(deptIds) && "1"
                    .equals(SystemTools.getInstance().getValue("org_act_switch"))) {
                param.setParams("dataDeptStr",
                        " and dept_id in(" + StrUtil.strArrayToStr(deptIds.split(","), ",", "'")
                                + ")");
            }
        }

        /**机构数据权限条件*/
        if (StrUtil.isNotNull(String.valueOf(vo.getParams("dataOrgId")))) {
            String dataOrg = String.valueOf(vo.getParams("dataOrgId"));
            sb.append(
                    " and userId in( select userId from DataRight where dataName='org' and dataKey='"
                            + dataOrg + "' )");
            param.setParams("dataOrgStr",
                    " and user_Id in( select user_Id from uct_data_right where data_Name='org' and data_Key='"
                            + dataOrg + "' )");
        } else {
            String orgtIds = String.valueOf(vo.getParams("dataOrgIds"));
            if (Validator.isNotNull(orgtIds) && "1"
                    .equals(SystemTools.getInstance().getValue("org_act_switch"))) {
                param.setParams("dataOrgStr",
                        " and org_id in( " + StrUtil.strArrayToStr(orgtIds.split(","), ",", "'")
                                + ")");
            }
        }

        if (Validator.isNotNull(String.valueOf(vo.getParams("userEname")))) {
            sb.append(" and userEname like '%" + String.valueOf(vo.getParams("userEname")) + "%'");
            param.setParams("userEname", "'%" + String.valueOf(vo.getParams("userEname")) + "%'");
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("userCname")))) {
            sb.append(" and userCname like '%" + String.valueOf(vo.getParams("userCname")) + "%'");
            param.setParams("userCname", "'%" + String.valueOf(vo.getParams("userCname")) + "%'");
        }

        if (Validator.isNotNull(String.valueOf(vo.getParams("sysEname")))) {
            sb.append(" and sysEname = :sysEname");
            param.setParams("sysEname", String.valueOf(vo.getParams("sysEname")));
        }
        String orgId = String.valueOf(vo.getParams("orgId"));
        String orgIds = getOrgIds(orgId);
        if (Validator.isNull(orgIds) && Validator.isNotNull(orgId)) {
            sb.append(" and orgId=:orgId");
            param.setParams("orgId", String.valueOf(vo.getParams("orgId")));
        } else {
            sb.append(" and orgId in (").append(orgIds).append(" ) ");
            param.setParams("orgIds", orgIds);
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("orgEname")))) {
            sb.append(" and orgEname = :orgEname");
            param.setParams("orgEname", String.valueOf(vo.getParams("orgEname")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("deptId")))) {
            sb.append(" and deptId = :deptId");
            param.setParams("deptId", String.valueOf(vo.getParams("deptId")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("appUid")))) {
            sb.append(" and appUid = :appUid");
            param.setParams("appUid", String.valueOf(vo.getParams("appUid")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("appUname")))) {
            sb.append(" and appUname = :appUname");
            param.setParams("appUname", String.valueOf(vo.getParams("appUname")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("userType")))) {
            sb.append(" and userType = :userType");
            param.setParams("userType", String.valueOf(vo.getParams("userType")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("province")))) {
            sb.append(" and province = :province");
            param.setParams("province", String.valueOf(vo.getParams("province")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("city")))) {
            sb.append(" and city = :city");
            param.setParams("city", String.valueOf(vo.getParams("city")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("address")))) {
            sb.append(" and address = :address");
            param.setParams("address", String.valueOf(vo.getParams("address")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("company")))) {
            sb.append(" and company = :company");
            param.setParams("company", String.valueOf(vo.getParams("company")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("position")))) {
            sb.append(" and position = :position");
            param.setParams("position", String.valueOf(vo.getParams("position")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("specField")))) {
            sb.append(" and specField = :specField");
            param.setParams("specField", String.valueOf(vo.getParams("specField")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("graduate")))) {
            sb.append(" and graduate = :graduate");
            param.setParams("graduate", String.valueOf(vo.getParams("graduate")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("school")))) {
            sb.append(" and school = :school");
            param.setParams("school", String.valueOf(vo.getParams("school")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("education")))) {
            sb.append(" and education = :education");
            param.setParams("education", String.valueOf(vo.getParams("education")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("birthday")))) {
            sb.append(" and birthday = :birthday");
            param.setParams("birthday", String.valueOf(vo.getParams("birthday")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("userSex")))) {
            sb.append(" and userSex = :userSex");
            param.setParams("userSex", String.valueOf(vo.getParams("userSex")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("cardType")))) {
            sb.append(" and cardType = :cardType");
            param.setParams("cardType", String.valueOf(vo.getParams("cardType")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("cardNum")))) {
            sb.append(" and cardNum = :cardNum");
            param.setParams("cardNum", String.valueOf(vo.getParams("cardNum")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("email")))) {
            sb.append(" and email = :email");
            param.setParams("email", String.valueOf(vo.getParams("email")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("phone")))) {
            sb.append(" and phone = :phone");
            param.setParams("phone", String.valueOf(vo.getParams("phone")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("mobile")))) {
            sb.append(" and mobile = :mobile");
            param.setParams("mobile", String.valueOf(vo.getParams("mobile")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("fax")))) {
            sb.append(" and fax = :fax");
            param.setParams("fax", String.valueOf(vo.getParams("fax")));
        }

        if (Validator.isNotNull(String.valueOf(vo.getParams("userRemark")))) {
            sb.append(" and userRemark = :userRemark");
            param.setParams("userRemark", String.valueOf(vo.getParams("userRemark")));
        }

        if (Validator.isNotNull(String.valueOf(vo.getParams("deptName")))) {
            sb.append(" and deptName = :deptName");
            param.setParams("deptName", String.valueOf(vo.getParams("deptName")));
        }
        if (Validator.isNotNull(String.valueOf(vo.getParams("bjcaUserid")))) {
            sb.append(" and bjcaUserid = :bjcaUserid");
            param.setParams("bjcaUserid", String.valueOf(vo.getParams("bjcaUserid")));
        }
        return sb.toString();
    }

    private String getRoleIdStr(String roleId) {
        StringBuffer str = new StringBuffer();
        str.append(" and user_Id in(select user_Id from uct_role_give where role_Id='" + roleId
                + "') ");
        return str.toString();
    }

    private String getUserIds(String ids) {
        String uids[] = ids.split(",");
        String result = "";
        for (int i = 0; i < uids.length; i++) {
            if (i == uids.length - 1) {
                result += "'" + uids[i] + "'";
            } else {
                result += "'" + uids[i] + "',";
            }
        }
        return result;
    }

    private String getOrgIds(String orgId) {
        if ("1".equals(SystemTools.getInstance().getValue("org_act_switch")) && StrUtil
                .isNotNull(orgId)) {//是否开启管理子机构
            ParamsVo<Org> vo = new ParamsVo<Org>();
            Org org = new Org();
            org.setFatherId(orgId);
            vo.setObj(org);
            List<Org> orgs = orgManager.getList(vo);
            if (!Validator.isEmpty(orgs)) {
                int count = orgs.size();
                StringBuffer sb = null;
                if (orgId.indexOf(",") != -1) {
                    sb = new StringBuffer(StrUtil.strArrayToStr(orgId.split(","), ",", "'"));
                } else {
                    sb = new StringBuffer("'" + orgId + "',");
                }

                for (int i = 0; i < count; i++) {
                    if (i == count - 1) {
                        sb.append("'" + orgs.get(i).getOrgId() + "'");
                    } else {
                        sb.append("'" + orgs.get(i).getOrgId() + "',");
                    }
                }
                return sb.toString();
            } else {
                if (orgId.indexOf(",") != -1) {
                    return StrUtil.strArrayToStr(orgId.split(","), ",", "'");
                }
            }
        } else {
            if (StrUtil.isNotNull(orgId) && orgId.indexOf(",") != -1) {
                return StrUtil.strArrayToStr(orgId.split(","), ",", "'");
            }
        }
        return "";
    }

    //权限标识
    private String actEnameStr(String actEname) {
        StringBuffer str = new StringBuffer();
        str.append(" and (");
        str.append(
                " user_Id in (select role_id from uct_act_give where act_Id in (select act_Id from uct_act where act_Ename='"
                        + actEname + "') )");
        str.append(
                " or user_Id in (select user_Id from uct_role_give where role_Id in(select role_Id from uct_act_give where act_Id in(select act_Id from uct_act where act_Ename='"
                        + actEname + "')) )");
        str.append(" ) ");
        return str.toString();
    }

    //操作权限条件
    private String getactStr(String actId) {
        StringBuffer sb = new StringBuffer();
        sb.append(" and (");
        sb.append(" user_Id in ( select role_id from uct_act_give where act_Id='" + actId + "' )");
        sb.append(" or user_Id in ( ");
        sb.append(" select user_Id from uct_role_give where role_Id in(");
        sb.append(" select role_Id from uct_act_give where act_Id ='" + actId + "' )");
        sb.append(" ) ) ");
        return sb.toString();
    }

    public void setUserDao(IDao userDao) {
        this.userDao = userDao;
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

}
